package com.cxx.autoconfigure.serializer;

import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;

import java.util.Collection;
import java.util.List;

public class MyBeanSerializerModifier extends BeanSerializerModifier {
    @Override
    public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BeanDescription beanDesc, List<BeanPropertyWriter> beanProperties) {
        //循环所有的beanPropertyWriter
        for (BeanPropertyWriter beanProperty : beanProperties) {
            // 判断字段的类型，如果是array，list，set则注册nullSerializer
            Class<?> clazz = beanProperty.getType().getRawClass();
            if (clazz.isArray() || Collection.class.isAssignableFrom(clazz)) {
                beanProperty.assignNullSerializer(new NullArrayJsonSerializer());
            } else if (CharSequence.class.isAssignableFrom(clazz) || Character.class.isAssignableFrom(clazz)) {
                beanProperty.assignNullSerializer(new NullStringJsonSerializer());
            }
        }

        return beanProperties;
    }
}
